package com.runfast.waimai.web.controller.Runfastbusinesscontroller;

/**
 * @Created by Ptkc on 2018/7/25 10:57.
 */

import com.runfast.common.utils.SessionContext;
import com.runfast.common.web.entity.Result;
import com.runfast.waimai.dao.model.*;
import com.runfast.waimai.service.RunfastBusinessService;
import com.runfast.waimai.service.RunfastGoodsSellChildrenService;
import com.runfast.waimai.service.RunfastGoodsSellRecordService;
import com.runfast.waimai.service.RunfastWithdrawService;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 商家提现转账
 */
@Slf4j
@RestController
@RequestMapping("/server/business")
public class BusinessSalesCountController {

    @Autowired
    private RunfastWithdrawService rw;
    @Autowired
    private RunfastBusinessService rb;
    @Autowired
    private RunfastGoodsSellRecordService rg;
    @Autowired
    private RunfastGoodsSellChildrenService rc;

    private ExportExcel ex;

    private SimpleDateFormat sdf3 = new SimpleDateFormat("yyyy-MM-dd");

    @RequestMapping(value="salesCountExport")
    public Result exportBusinessSales(HttpServletResponse response, @RequestParam(value = "beginTime", required = false) String beginTime, @RequestParam(value = "endTime", required = false) String endTime ) {
        if (beginTime == null || endTime == null)
            return Result.fail(null, "请选择时间");
        Date bTime,eTime;
        try {
            bTime = sdf3.parse(beginTime);
            eTime = sdf3.parse(endTime);
        } catch (ParseException e) {
            e.printStackTrace();
            return Result.fail(null, "时间格式错误");
        }
        HSSFWorkbook wb = null;

        BaseUser admin = SessionContext.getAdmin();
        WaiMaiRunfastAgentaccounts agentAccounts= SessionContext.getCurrentRunfastAgentaccounts();
        RunfastBusinessAccounts accounts = SessionContext.getRunfastBusinessAccounts();
        /*User admin = super.getAdmin();
        AgentAccounts agentAccounts = super.getAgentAccounts();
        BusinessAccounts accounts = super.getBusinessAccounts();*/
        List<Map<String, Object>> list = null;
        int type=0;
        long start = System.currentTimeMillis();
        Map<String, Object> map = new HashMap<>();
        map.put("beginTime",bTime);
        map.put("endTime",eTime);//按照时间段赛选

        if(admin!=null && admin.getType()==3 && accounts!=null){//商家帐号登录---只能看自己商家的
            type=0;
            map.put("businessId",accounts.getBusinessid());
            map.put("businessName",accounts.getBusinessname());
        }else if(admin!=null && admin.getType()==2 && agentAccounts!=null){//代理商---只看到自己代理的商家
            type=1;
            map.put("agentId",agentAccounts.getAgentid());
        }else if(admin!=null && admin.getType()==1){//后台管理员---查看全部的
            type=2;
        }
        list = rg.selectSalesCountExport(map);
        long end = System.currentTimeMillis();
        System.out.println("stat time="+(end-start));
        List<RunfastGoodsSellRecord> recordList = new ArrayList<RunfastGoodsSellRecord>();
        start = System.currentTimeMillis();
        if(list!=null && list.size()>0){
            //批量获取要查询的商家,再一次性查询出来
            List<Integer> ids = new ArrayList<Integer>();
            for(Map<String,Object> map1 : list){
                if(map1.get("id")!=null){
                    Integer id = (Integer) map1.get("id");
                    if(id!=null){
                        ids.add(id);
                    }
                }
            }
            RunfastGoodsSellRecordExample recordExample = new RunfastGoodsSellRecordExample();
            RunfastGoodsSellRecordExample.Criteria recordCriteria = recordExample.createCriteria();
            if(ids!=null && ids.size()>0)
                recordCriteria.andBusinessidIn(ids);
            if(beginTime!=null && endTime!=null)
                recordCriteria.andCreatetimeBetween(bTime, eTime);
            recordCriteria.andStatusEqualTo(8);
            List<RunfastGoodsSellRecord> records = rg.selectByExample(recordExample);
            if(records!=null && records.size()>0){
                //批量获取子订单再用代码匹配
                List<String> orderCodeList = new ArrayList<String>();
                for(RunfastGoodsSellRecord gsr:records){
                    orderCodeList.add(gsr.getOrdercode());
                }
                if(orderCodeList.size()>0){
                    //根据订单号,放到对应订单里,如果数据量大，可能会有异常
                    RunfastGoodsSellChildrenExample childrenExample = new RunfastGoodsSellChildrenExample();
                    RunfastGoodsSellChildrenExample.Criteria childrenExampleCriteria = childrenExample.createCriteria();
                    childrenExampleCriteria.andOrdercodeIn(orderCodeList);
                    List<RunfastGoodsSellChildren> gsrcList = rc.selectByExample(childrenExample);
                    if(gsrcList!=null && gsrcList.size()>0){
                        Map<String,List<RunfastGoodsSellChildren>> subMap = new HashMap<String,List<RunfastGoodsSellChildren>>();
                        //批量查询出来的子订单按所属订单生成不同的list
                        for(RunfastGoodsSellChildren gsrc:gsrcList){
                            if(gsrc.getOrdercode()!=null){
                                List<RunfastGoodsSellChildren> subList = subMap.get(gsrc.getOrdercode());
                                if(subList==null){
                                    subList = new ArrayList<RunfastGoodsSellChildren>();
                                    subMap.put(gsrc.getOrdercode(), subList);
                                }
                                subList.add(gsrc);
                            }
                        }
                        //放到订单里
                        for(RunfastGoodsSellRecord gsr:records){
                            gsr.setGoodsSellRecordChildren(subMap.get(gsr.getOrdercode()));
                        }
                    }
                }
                recordList.addAll(records);
            }
        }
        end = System.currentTimeMillis();
        System.out.println("list time="+(end-start));
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd_HH：mm");
        String fileName = beginTime+"至"+endTime+"商家销量统计("+sdf.format(new Date())+")"+".xls";

        start = System.currentTimeMillis();
        WriteExcel writeExcel = new WriteExcel();
        wb = writeExcel.countBusinessSales(list, recordList,type);
        createXLS(response,wb,fileName);// 生成XLS文件
        end = System.currentTimeMillis();
        System.out.println("write time="+(end-start));
        return Result.ok("");
    }

    /**
     * 生成XLS文件
     * @param response
     * @param wb 生成的excel内容
     * @param filename 生成的文件名
     * */
    private void createXLS(HttpServletResponse response, HSSFWorkbook wb,String filename) {

        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        // 设置response参数，可以打开下载页面
        response.reset();
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        ServletOutputStream out;
        try {
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes(), "iso-8859-1"));
            out = response.getOutputStream();
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            wb.write(os);
            byte[] content = os.toByteArray();
            InputStream is = new ByteArrayInputStream(content);

            bis = new BufferedInputStream(is);
            bos = new BufferedOutputStream(out);
            byte[] buff = new byte[2048];
            int bytesRead;
            // Simple read/write loop.
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        } catch (IOException e1) {
            e1.printStackTrace();
        } finally {
            if (bis != null){
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bos != null){
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    /*
    * 批量审核/反审核
    */
    @GetMapping("/batchAudit")
    @Transactional
    public Result batchAudit(Integer opr, String ids){
        /* opr 1,审核通过2,审核不通过3,处理 */
        /* Status状态:0待审核,1通过,2不通过*/
        boolean all = true;
        if(opr==null)
            return Result.fail(null,"操作传值为空");
        if( ids==null )//&& ids.length==0
            return Result.fail(null,"id为空");
        String[] idss = ids.split(",");
        //批量审核通过
        if (opr == 1) {
            for (int i = 0; i < idss.length; i++) {
                RunfastWithdraw runfastWithdraw = rw.selectByPrimaryKey(Integer.valueOf(idss[i]));
                if(runfastWithdraw != null){
                    if(runfastWithdraw.getStatus()==0){//待审核状态修改为通过
                        runfastWithdraw.setStatus(1);//改为1，通过
                        runfastWithdraw = checkUser(opr, runfastWithdraw);
                        rw.updateByPrimaryKeySelective(runfastWithdraw);
                    }else
                        all = false;
                }
            }
        }
        //批量审核不通过
        if (opr == 2) {
            for (int i = 0; i < idss.length; i++) {
                RunfastWithdraw runfastWithdraw = rw.selectByPrimaryKey(Integer.valueOf(idss[i]));
                if(runfastWithdraw != null){
                    if(runfastWithdraw.getStatus()==0){//待审核状态修改为通过
                        runfastWithdraw.setStatus(2);//改为1，不通过runfastWithdraw.setAtudittime(new Date());
                        runfastWithdraw = checkUser(opr, runfastWithdraw);
                        rw.updateByPrimaryKeySelective(runfastWithdraw);
                    }else
                        all = false;
                }
            }
        }
        //批量处理
        if (opr == 3) {
            for (int i = 0; i < idss.length; i++) {
                RunfastWithdraw runfastWithdraw = rw.selectByPrimaryKey(Integer.valueOf(idss[i]));
                if(runfastWithdraw != null){
                    if(runfastWithdraw.getState()==0){//未处理状态改为已处理
                        runfastWithdraw.setState(1);//改为1，已处理
                        runfastWithdraw = checkUser(opr, runfastWithdraw);
                        rw.updateByPrimaryKeySelective(runfastWithdraw);
                    }else
                        all = false;
                }
            }
        }
        /*//批量反审核
        if (opr == ) {
            for (int i = 0; i < idss.length; i++) {
                RunfastWithdraw runfastWithdraw = rw.selectByPrimaryKey(Integer.valueOf(idss[i]));
                if(runfastWithdraw != null){
                    if(runfastWithdraw.getState()==0){//未处理之前修改为待审核
                        runfastWithdraw.setStatus(0);//改为0，待审核
                        rw.updateByPrimaryKeySelective(runfastWithdraw);
                    }else
                        all = false;
                }
            }
        }*/
        if (all)
            return Result.ok("");
        else
            return Result.ok("部分状态不能修改");
    }

    private RunfastWithdraw checkUser(Integer opr, RunfastWithdraw runfastWithdraw) {
        BaseUser admin = SessionContext.getAdmin();
        WaiMaiRunfastAgentaccounts agentAccounts= SessionContext.getCurrentRunfastAgentaccounts();
        RunfastBusinessAccounts accounts = SessionContext.getRunfastBusinessAccounts();
        if(opr==1 || opr==2){
            runfastWithdraw.setAtudittime(new Date());
            if(admin!=null && admin.getType()==3 && accounts!=null){//商家帐号登录
                runfastWithdraw.setAtuditid(accounts.getBusinessid());
                runfastWithdraw.setAtuditname(accounts.getBusinessname());
            }else if(admin!=null && admin.getType()==2 && agentAccounts!=null){//代理商
                runfastWithdraw.setAtuditid(agentAccounts.getAgentid());
                runfastWithdraw.setAtuditname(agentAccounts.getAgentname());
            }else if(admin!=null && admin.getType()==1){//后台管理员
                runfastWithdraw.setAtuditid(admin.getId());
                runfastWithdraw.setAtuditname(admin.getRealname());
            }
        }
        if(opr==3){
            runfastWithdraw.setReadytime(new Date());
            if(admin!=null && admin.getType()==3 && accounts!=null){//商家帐号登录
                runfastWithdraw.setRid(accounts.getBusinessid());
                runfastWithdraw.setReadrname(accounts.getBusinessname());
            }else if(admin!=null && admin.getType()==2 && agentAccounts!=null){//代理商
                runfastWithdraw.setRid(agentAccounts.getAgentid());
                runfastWithdraw.setReadrname(agentAccounts.getAgentname());
            }else if(admin!=null && admin.getType()==1){//后台管理员
                runfastWithdraw.setRid(admin.getId());
                runfastWithdraw.setReadrname(admin.getRealname());
            }
        }
        return runfastWithdraw;
    }

    /*
     * 商家销量统计（详情）
     */
    @GetMapping("/businessSalesDetails")
    public Result businessSalesDetails(Integer id, String beginTime, String endTime, Integer agentId, @PageableDefault Pageable pageable){
        if (beginTime == null || endTime == null)
            return Result.fail(null, "请选择时间");
        Date bTime,eTime;
        try {
            bTime = sdf3.parse(beginTime);
            eTime = sdf3.parse(endTime);
        } catch (ParseException e) {
            e.printStackTrace();
            return Result.fail(null, "时间格式错误");
        }
        RunfastGoodsSellRecordExample sellRecordExample = new RunfastGoodsSellRecordExample();
        RunfastGoodsSellRecordExample.Criteria criteria = sellRecordExample.createCriteria();
        criteria.andStatusEqualTo(8);
        if(id!=null)
            criteria.andBusinessidEqualTo(id);
        if(beginTime!=null && endTime!=null)
            criteria.andCreatetimeBetween(bTime, eTime);
        if(agentId!=null)
            criteria.andAgentidEqualTo(agentId);

        List<RunfastGoodsSellRecord> list = rg.selectByExampleWithPageable(sellRecordExample, pageable);
        Integer total = rg.countByExample(sellRecordExample);
        Map<Object,Object> map=new HashMap<Object, Object>();
        map.put("list",list);
        map.put("total",total);
        return Result.ok(null,map);
    }

    /*
     * 代理商销量统计
     */
    @GetMapping("/agentSalesCount")
    public Result agentSalesCount(RunfastGoodsSellRecord sellRecord, @PageableDefault Pageable pageable){
        return Result.ok(null);
    }

    /*
     * 商家销量统计
     */
    @GetMapping("/businessSalesCount")
    public Result businessSalesCount(String beginTime, String endTime, String agentId, String businessId, String businessName, @PageableDefault Pageable pageable){
        if (beginTime == null || endTime == null)
            return Result.fail(null, "请选择时间");
        Date bTime,eTime;
        try {
            bTime = sdf3.parse(beginTime);
            eTime = sdf3.parse(endTime);
        } catch (ParseException e) {
            e.printStackTrace();
            return Result.fail(null, "时间格式错误");
        }
        Map<String, Object> map = new HashMap<>();
        if (beginTime != null && endTime != null) {
            map.put("beginTime",bTime);
            map.put("endTime",eTime);
        }
        if(agentId!=null)
            map.put("agentId",agentId);
        if(businessId!=null)
            map.put("businessId",businessId);
        if(businessName!=null)
            map.put("businessName",businessName);
        List<Map<String,Object>> list = rg.businessSalesCount(map);

        RunfastGoodsSellRecordExample sellRecordExample = new RunfastGoodsSellRecordExample();
        RunfastGoodsSellRecordExample.Criteria criteria = sellRecordExample.createCriteria();
        criteria.andStatusEqualTo(8);
        if(beginTime != null && endTime != null)
            criteria.andCreatetimeBetween(bTime, eTime);
        if(businessName != null)
            criteria.andBusinessnameLike("%"+businessName+"%");
        if(agentId != null)
            criteria.andAgentidEqualTo(Integer.parseInt(agentId));
        sellRecordExample.setDistinct(true);
        Integer total = rg.countByBusinessSalesCount(sellRecordExample);
        Map<Object,Object> mapOut=new HashMap<Object, Object>();
        mapOut.put("list",list);
        mapOut.put("total",total);
        return Result.ok(null,mapOut);
    }

    //@RequestMapping("/salesCountExport")
    public Result export(HttpServletResponse response, @RequestParam(value = "beginTime", required = false) String beginTime, @RequestParam(value = "endTime", required = false) String endTime) {
        //System.out.println(beginTime+"----------------"+endTime);
        if (beginTime == null || endTime == null)
            return Result.fail(null, "请选择时间");
        try {
            OutputStream out = response.getOutputStream();
            Result result = group(beginTime, endTime);
            if (result.isSuccess()) {
                response.setCharacterEncoding("UTF-8");
                response.setContentType("application/vnd.ms-excel");
                String fileName = new String(("商家销量统计_" + beginTime + "至" + endTime + String.valueOf(System.currentTimeMillis())).getBytes(), "UTF-8");
                response.setHeader("Content-disposition", "attachment;fileName=" + fileName + ".xls");//URLEncoder.encode(fileName, "utf-8")
                ex.export(out);
                return result;
            } else
                return result;
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail(null, "导出失败");
        }
    }

    public Result group(String beginTime, String endTime) {
        Map<String, Object> map = new HashMap<>();
        try {
            map.put("beginTime",sdf3.parse(beginTime));
            map.put("endTime",sdf3.parse(endTime));//按照时间段赛选
        } catch (ParseException e) {
            e.printStackTrace();
            return Result.fail(null, "时间格式错误");
        }
        List<Map<String,Object>> rfsgrList = rg.selectSalesCountExport(map);
        if (rfsgrList != null && !rfsgrList.isEmpty()) {
            //拼装Excel数据
            String title = "商家销售统计记录";
            String[] rowsName = new String[]{"商家编号", "代理商", "商家名称", "订单数量", "商品数量", "实付金额", "商家部分总金额", "商家收入（元）", "商家补贴（元）", "已提现金额", "未提现金额", "配送费", "退款金额", "代理商抽成", "上级代理商抽成", "平台抽成", "优惠金额", "提成系数", "配送方式"};
            /*            select a.id as businessId, b.name as agentName,a.name as businessName,count(distinct d.pid)as orderNum,count(d.id) as goodsNum,sum(c.totalpay)as totalPay,sum(c.businesspay)as businessPay,sum(c.businesspay-c.businessget)as businessTotal,sum(c.subsidy)as subsidy,c.iswithdraw as isWithdraw,sum(c.showps)as showps,sum(c.refund)as refund,sum(c.agentBusget)as agentBusget,sum(agentBusget2)as agentBusget2,sum(c.agentget)as agentget,sum(yhprice)as yhprice,a.coefficient as coefficient,a.isDeliver as isDeliver*/
            List<Object[]> dataList = new ArrayList<Object[]>();
            for (int i = 0; i<rfsgrList.size(); i++){
                Map<String, Object> map1 = rfsgrList.get(i);
                Object[] objs = new Object[rowsName.length];
                objs[1] = map1.get("agentName");
                objs[2] = map1.get("businessName");
                objs[3] = map1.get("orderNum");
                objs[4] = map1.get("goodsNum");
                objs[5] = map1.get("totalPay");
                objs[6] = map1.get("businessPay");
                objs[7] = map1.get("businessTotal");
                objs[8] = map1.get("subsidy");
                objs[9] = map1.get("isWithdraw");
                objs[10] = map1.get("isWithdraw");
                objs[11] = map1.get("showps");
                objs[12] = map1.get("refund");
                objs[13] = map1.get("agentBusget");
                objs[14] = map1.get("agentBusget2");
                objs[15] = map1.get("agentget");
                objs[16] = map1.get("yhprice");
                objs[17] = map1.get("coefficient");
                objs[18] = map1.get("isDeliver");
                dataList.add(objs);
            }
            if (dataList.isEmpty() && dataList.size()<1)
                return Result.fail(null, "没有匹配的数据");
            ex = new ExportExcel(title, rowsName, dataList);
            log.info("导出成功！");
            return Result.ok("");
        } else {
            return Result.fail(null, "没有匹配的数据");
        }
    }
}
